<template>
  <div>
    <vxe-grid ref="xGrid" v-bind="gridOptions" v-on="gridEvent" />
  </div>
</template>

<script lang="ts" setup>
  import { onMounted, reactive, ref } from "vue"
  import { VXETable, VxeGridInstance, VxeGridListeners, VxeGridProps } from "vxe-table"
  import XEUtils from "xe-utils"
  import { saveOrUpdateGenTableInfo, listGenTableColumn, getGenTable } from "../../codeGen.api"

  interface RowVO {
    [key: string]: any
  }

  const serveApiUrl = "https://api.vxetable.cn/demo"

  const xGrid = ref<VxeGridInstance<RowVO>>()

  const gridOptions = reactive<VxeGridProps<RowVO>>({
    border: true,
    showHeaderOverflow: true,
    showOverflow: true,
    keepSource: true,
    id: "full_edit_1",
    rowConfig: {
      keyField: "id",
      isHover: true,
    },
    columnConfig: {
      resizable: true,
    },
    customConfig: {
      storage: true,
      checkMethod({ column }) {
        if (["nickname", "role"].includes(column.field)) {
          return false
        }
        return true
      },
    },
    sortConfig: {
      trigger: "cell",
      remote: true,
    },
    filterConfig: {
      remote: true,
    },
    pagerConfig: {
      enabled: true,
      // currentPage: 1,
      pageSize: 10,
      pageSizes: [5, 10, 15, 20, 50, 100, 200, 500, 1000],
    },
    toolbarConfig: {
      buttons: [
        { code: "insert_actived", name: "新增" },
        { code: "delete", name: "直接删除" },
        { code: "mark_cancel", name: "删除/取消" },
      ],
    },
    proxyConfig: {
      seq: true, // 启用动态序号代理，每一页的序号会根据当前页数变化
      sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
      filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为
      form: true, // 启用表单代理，当点击表单提交按钮时会自动触发 reload 行为
      props: {
        // 对应响应结果 Promise<{ result: [], page: { total: 100 } }>
        result: "data", // 配置响应结果列表字段
        total: "page.total", // 配置响应结果总页数字段
      },
      // 只接收Promise，具体实现自由发挥
      ajax: {
        // 当点击工具栏查询按钮或者手动提交指令 query或reload 时会被触发
        query: ({ page, sorts, filters, form }) => {
          const queryParams: any = Object.assign({}, form)
          // 处理排序条件
          const firstSort = sorts[0]
          if (firstSort) {
            queryParams.sort = firstSort.field
            queryParams.order = firstSort.order
          }
          // 处理筛选条件
          filters.forEach(({ field, values }) => {
            queryParams[field] = values.join(",")
          })
          return listGenTableColumn("521499675792389")
        },
        // 当点击工具栏删除按钮或者手动提交指令 delete 时会被触发
        delete: ({ body }) => {
          return fetch(`${serveApiUrl}/api/pub/save`, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(body),
          }).then((response) => response.json())
        },
        // 当点击工具栏保存按钮或者手动提交指令 save 时会被触发
        save: ({ body }) => {
          return fetch(`${serveApiUrl}/api/pub/save`, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(body),
          }).then((response) => response.json())
        },
      },
    },
    columns: [
      { type: "checkbox", title: "ID", width: 120, isHidden: true },
      {
        field: "columnName",
        title: "Name",
        sortable: true,
        titlePrefix: { message: "名称必须填写！" },
        editRender: { name: "input", attrs: { placeholder: "请输入名称" } },
      },
      {
        field: "role",
        title: "Role",
        sortable: true,
        titlePrefix: { useHTML: true, content: '点击链接：<a class="link" href="https://vxetable.cn" target="_blank">vxe-table官网</a>' },
        filters: [
          { label: "前端开发", value: "前端" },
          { label: "后端开发", value: "后端" },
          { label: "测试", value: "测试" },
          { label: "程序员鼓励师", value: "程序员鼓励师" },
        ],
        filterMultiple: false,
        editRender: { name: "input", attrs: { placeholder: "请输入角色" } },
      },
      { field: "email", title: "Email", width: 160, editRender: { name: "$input", props: { placeholder: "请输入邮件" } } },
      { field: "nickname", title: "Nickname", editRender: { name: "input", attrs: { placeholder: "请输入昵称" } } },
      {
        field: "sex",
        title: "Sex",
        filters: [
          { label: "男", value: "1" },
          { label: "女", value: "0" },
        ],
        editRender: { name: "$select", options: [], props: { placeholder: "请选择性别" } },
      },
      { field: "age", title: "Age", visible: false, sortable: true, editRender: { name: "$input", props: { type: "number", min: 1, max: 120 } } },
      {
        field: "amount",
        title: "Amount",
        formatter({ cellValue }) {
          return cellValue ? `￥${XEUtils.commafy(XEUtils.toNumber(cellValue), { digits: 2 })}` : ""
        },
        editRender: { name: "$input", props: { type: "float", digits: 2, placeholder: "请输入数值" } },
      },
      {
        field: "updateDate",
        title: "Update Date",
        width: 160,
        visible: false,
        sortable: true,
        formatter({ cellValue }) {
          return XEUtils.toDateString(cellValue, "yyyy-MM-dd HH:ss:mm")
        },
      },
      {
        field: "createDate",
        title: "Create Date",
        width: 160,
        visible: false,
        sortable: true,
        formatter({ cellValue }) {
          return XEUtils.toDateString(cellValue, "yyyy-MM-dd")
        },
      },
    ],
    checkboxConfig: {
      labelField: "id",
      reserve: true,
      highlight: true,
      range: true,
    },
    editRules: {
      name: [
        { required: true, message: "app.body.valid.rName" },
        { min: 3, max: 50, message: "名称长度在 3 到 50 个字符" },
      ],
      email: [{ required: true, message: "邮件必须填写" }],
      role: [{ required: true, message: "角色必须填写" }],
    },
    editConfig: {
      trigger: "click",
      mode: "row",
      showStatus: true,
    },
  })

  const gridEvent: VxeGridListeners<RowVO> = {
    proxyQuery() {
      console.log("数据代理查询事件")
    },
    proxyDelete() {
      console.log("数据代理删除事件")
    },
    proxySave() {
      console.log("数据代理保存事件")
    },
  }

  onMounted(() => {
    const sexList = [
      { label: "女", value: "0" },
      { label: "男", value: "1" },
    ]
    const { formConfig, columns } = gridOptions
    if (columns) {
      const sexColumn = columns[5]
      if (sexColumn && sexColumn.editRender) {
        sexColumn.editRender.options = sexList
      }
    }
    if (formConfig && formConfig.items) {
      const sexItem = formConfig.items[4]
      if (sexItem && sexItem.itemRender) {
        sexItem.itemRender.options = sexList
      }
    }
  })
</script>
